package com.itheima.appserver.service;

import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.appserver.excepiton.BusinessException;
import com.itheima.appserver.excepiton.ErrorResult;
import com.itheima.appserver.interceptor.UserThreadLocal;
import com.itheima.commons.pojo.domain.UserInfo;
import com.itheima.commons.utils.FaceDetectUtil;
import com.itheima.commons.utils.UploadPicUtil;
import com.itheima.dubbo.interfaces.UserInfoApi;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

/**
 * @author yaohu
 * @date 2021/12/5
 * @Version 1.0
 * @describe
 */
@Service
public class UserInfoService {

    @Reference
    private UserInfoApi userInfoAPI;

    public void loginReginfo(Map<String, String> params) {

        // 判断参数是否合法 参数必须不为空
        if (StrUtil.hasBlank(params.get("gender"), params.get("nickname"), params.get("birthday"), params.get("city"))) {
            throw new BusinessException(ErrorResult.paramIsEmpty());
        }

        // 如果都不为空，调用dubbo服务插入到数据库中 userInfo
        userInfoAPI.addUserInfo(UserInfo.builder()
                .userId(UserThreadLocal.getUserId())
                .sex("man".equalsIgnoreCase(params.get("gender")) ? 1 : 2)
                .nickName(params.get("nickname"))
                .birthday(params.get("birthday"))
                .city(params.get("city"))
                .build());
    }

    public void loginReginfoHead(MultipartFile headPhoto) {

        // 校验文件的格式 png jpg jpeg
        if (!StrUtil.endWithAnyIgnoreCase(headPhoto.getOriginalFilename(), ".png", ".jpg", ".jpeg")) {
            throw new BusinessException(ErrorResult.photoFormatError());
        }

        // 校验文件大小 大于2M 抛出异常
        if (headPhoto.getSize() / 1024 / 1024 >= 2) {
            throw new BusinessException(ErrorResult.photoSizeError());
        }

        // 人脸识别
        try {
            if (!FaceDetectUtil.detectFace(headPhoto.getBytes())) {
                throw new BusinessException(ErrorResult.faceRecognitionFailed());
            }
            // 上传阿里云OSS 返回地址
            String pictureUrl = UploadPicUtil.uploadPicture(headPhoto.getBytes(),
                    StrUtil.subAfter(headPhoto.getOriginalFilename(), ".", true));
            // 把地址更新到MySQL数据库中
            userInfoAPI.updateLogo(UserThreadLocal.getUserId(), pictureUrl);
        } catch (IOException e) {
            throw new BusinessException(ErrorResult.photoFormatError());
        }
    }
}
